package com.fcml.rbmq.study.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.fcml.rbmq.study.user.model.User;
import com.fcml.rbmq.study.user.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping(value = "register")
    public User register(@RequestBody User user) {
        String userJson = JSONObject.toJSONString(user);
        log.info("用户注册，注册信息:{}", userJson);

        String msgId = RandomUtil.getRandomUUID(20);
        Message message = MessageBuilder.withBody(userJson.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setCorrelationId(msgId)
                .build();
        CorrelationData correlationData = new CorrelationData(msgId);

        /**
         * 将msgId与Message的关系保存起来,放到缓存中.
         */
        redisTemplate.opsForHash().put("message", msgId, message);
        redisTemplate.opsForHash().put("exchange", msgId, "sms_captcha");
        redisTemplate.opsForHash().put("routingKey", msgId, "sms.captcha");

        //TODO 有些时候，由于某些原因发送端接收不到MQ的confirm，这条消息可能已经丢了，需要重新发送。
        //TODO 还需要定期查询缓存，查看消息的发送时间距现在是否已经超过了一定时间，超过了这个时间但是消息还存在缓存中，则消息很有可能已经丢了，发送端没有收到confirm，需要重新发送。
        //TODO 需要缓存的数据有点杂，redis这么设计好吗？

        rabbitTemplate.convertAndSend("sms_captcha", "sms.captcha", message, correlationData);
        return user;
    }

}
